package tij4.concurrent.source;

/*
    ReentranLoc上阻塞的任务具备可以被中断的能力
 */

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class BlockMutex {
    private Lock lock = new ReentrantLock();

    public BlockMutex() {
        lock.lock();
   }
    public void f() {
        try {
            lock.lockInterruptibly();   //获取锁定,除非当前线程是interrupted
            System.out.println("lock acquirred in f()");
        }catch (InterruptedException e) {
            System.out.println("Interrupted from lock acquisition in f()");
        }
    }
}

class Blocked2 implements Runnable {
    BlockMutex blockMutex = new BlockMutex();

    @Override
    public void run() {
        System.out.println("Waiting for f() in BlockedMutex");
        blockMutex.f();
        System.out.println("Broken out of blocked call");
    }
}

public class Interrupting2 {
    public static void main(String[] args) throws Exception{
        Thread thread = new Thread(new Blocked2());
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("Issuing t.interrupt()");
        thread.interrupt();
    }
}
